import numpy as np
import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 柯西中值定理的简单示例
def f(x):
    return x**2

def g(x):
    return x**3

def df(x):
    return 2*x

def dg(x):
    return 3*x**2

a, b = 1, 2
left_side = (f(b) - f(a)) / (g(b) - g(a))

# 寻找满足条件的点
found_point = None
for x in np.linspace(a, b, 1000):
    right_side = df(x) / dg(x)
    if abs(left_side - right_side) < 0.001:
        found_point = x
        print(f"在x={x:.3f}处满足柯西中值定理")
        print(f"左边: {left_side:.3f}, 右边: {right_side:.3f}")
        break

# ==================== 可视化部分 ====================

# 创建图形和子图
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 5))

# 1. 函数图像：f(x) 和 g(x)
x_plot = np.linspace(0.5, 2.5, 100)
ax1.plot(x_plot, f(x_plot), 'b-', label='f(x) = x^2', linewidth=2)
ax1.plot(x_plot, g(x_plot), 'r-', label='g(x) = x^3', linewidth=2)
ax1.scatter([a, b], [f(a), f(b)], color='blue', s=50, zorder=5)
ax1.scatter([a, b], [g(a), g(b)], color='red', s=50, zorder=5)
ax1.axvline(a, color='gray', linestyle='--', alpha=0.7)
ax1.axvline(b, color='gray', linestyle='--', alpha=0.7)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('函数 f(x) 和 g(x) 的图像')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 2. 参数曲线：(g(x), f(x))
x_param = np.linspace(a, b, 100)
ax2.plot(g(x_param), f(x_param), 'purple', linewidth=3, label='参数曲线 (g(x), f(x))')
ax2.scatter([g(a), g(b)], [f(a), f(b)], color='green', s=80, zorder=5, label='端点')

if found_point is not None:
    # 绘制弦和切线
    # 弦：连接端点的直线
    chord_x = [g(a), g(b)]
    chord_y = [f(a), f(b)]
    ax2.plot(chord_x, chord_y, 'orange', linestyle='--', linewidth=2, label='弦')
    
    # 切线：在找到的点处
    tangent_slope = df(found_point) / dg(found_point)
    tangent_x = np.linspace(g(found_point)-0.5, g(found_point)+0.5, 10)
    tangent_y = f(found_point) + tangent_slope * (tangent_x - g(found_point))
    ax2.plot(tangent_x, tangent_y, 'red', linewidth=2, label='切线')
    
    # 标记中值点
    ax2.scatter([g(found_point)], [f(found_point)], color='red', s=100, zorder=5, label='中值点')

ax2.set_xlabel('g(x)')
ax2.set_ylabel('f(x)')
ax2.set_title('参数空间中的柯西中值定理')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 3. 导函数比值的变化
x_deriv = np.linspace(a, b, 100)
right_sides = df(x_deriv) / dg(x_deriv)

ax3.axhline(left_side, color='orange', linestyle='--', linewidth=2, label='左边值 (常数)')
ax3.plot(x_deriv, right_sides, 'green', linewidth=2, label='右边值 df(x)/dg(x)')

if found_point is not None:
    ax3.axvline(found_point, color='red', linestyle=':', alpha=0.8, label=f'中值点 x={found_point:.3f}')
    ax3.scatter([found_point], [right_side], color='red', s=80, zorder=5)

ax3.set_xlabel('x')
ax3.set_ylabel('导函数比值')
ax3.set_title('左右两边值的变化')
ax3.legend()
ax3.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# ==================== 补充：验证定理的数值计算 ====================
print("\n" + "="*50)
print("柯西中值定理验证结果:")
print("="*50)
print(f"区间: [{a}, {b}]")
print(f"f(a) = {f(a):.3f}, f(b) = {f(b):.3f}")
print(f"g(a) = {g(a):.3f}, g(b) = {g(b):.3f}")
print(f"左边值 (f(b)-f(a))/(g(b)-g(a)) = {left_side:.3f}")

if found_point is not None:
    print(f"找到的中值点: x = {found_point:.3f}")
    print(f"该点的右边值 df(x)/dg(x) = {right_side:.3f}")
    print(f"绝对误差: {abs(left_side - right_side):.6f}")
else:
    print("未找到满足条件的点，请调整阈值或检查函数")
